import React, { useState, useEffect, useRef } from 'react';
import { Space, Table, Tag, Button, Popconfirm, message, Input, Upload, Image, Form } from 'antd';
import { UploadOutlined, DownloadOutlined, DeleteOutlined } from '@ant-design/icons';

import { getUserList, deleteCarousel, uploadCarouselForm, updateCarouselStatus } from '@/api/manage';
import { getHomeCarousel } from '@/api/home';
import { urlMap, imagesMap } from '@/utils';
import Dialog from '@/components/common/Dialog';

const { Search } = Input;

function HomeMan() {
    const [isOpen, setIsOpen] = useState(false);

    const [loading, setLoading] = useState(false);
    const [isRefresh, setIsRefresh] = useState(false);
    const [data, setData] = useState([]);
    const [form] = Form.useForm();

    const handleShelf = async (id) => {
        console.log('上架文章 ID:', id);
        await updateCarouselStatus(id, 'publish').then(() => {
            setIsRefresh(true);
            message.success('上架成功');
        });
    };

    const handleOffShelf = async (id) => {
        console.log('下架文章 ID:', id);
        await updateCarouselStatus(id, 'unpublish').then(() => {
            setIsRefresh(true);
            message.success('下架成功');
        });
    };

    const handleDelete = async (id) => {
        console.log('删除文章 ID:', id);
        await updateCarouselStatus(id, 'delete').then(() => {
            setIsRefresh(true);
            message.success('删除成功');
        });
    };

    const columns = [
        {
            title: 'id',
            dataIndex: 'homeImageId',
            key: 'homeImageId',
            render: (text) => <span>{text}</span>,
        },
        {
            title: '名称',
            dataIndex: 'title',
            key: 'title',
            width: 200,
            render: (text) => <span>{text}</span>,
        },
        {
            title: '图片',
            dataIndex: 'imagePath',
            key: 'imagePath',
            render: (url) => {
                console.log('url', url);
                return (
                    <Image
                        width={80}
                        src={urlMap.defaultUrl + imagesMap.homePicturePath + url}
                        preview={{ mask: '预览' }}
                        style={{
                            borderRadius: 4,
                            objectFit: 'cover',
                        }}
                    />
                );
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'green';
                let text = '展示中';
                if (status === 0) {
                    color = 'yellow';
                    text = '已下架';
                }
                return (
                    <Tag color={color} key={status}>
                        {text}
                    </Tag>
                );
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space split={<span className="ant-divider" />}>
                    {record.status === 0 ? (
                        <Button type="link" icon={<UploadOutlined />} onClick={() => handleShelf(record.homeImageId)}>
                            上架
                        </Button>
                    ) : (
                        <Popconfirm
                            title="提示"
                            description="确认要下架该图片吗?"
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => handleOffShelf(record.homeImageId)}
                        >
                            <Button type="link" style={{ color: '#fa8c16' }} icon={<DownloadOutlined />}>
                                下架
                            </Button>
                        </Popconfirm>
                    )}
                    <Popconfirm
                        title="提示"
                        description="确认要删除该图片吗?"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => handleDelete(record.homeImageId)}
                    >
                        <Button type="link" danger icon={<DeleteOutlined />}>
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // 处理查询逻辑
    const onSearch = (value) => {
        // if(value === ''){
        //   return message.error('查询内容不能为空');
        // }
        setLoading(true);
        getHomeCarousel(value)
            .then((res) => {
                if (res.code === 200) {
                    setData(res.data);
                    message.success('查询成功');
                }
            })
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        setLoading(true);
        getHomeCarousel()
            .then((res) => {
                if (res.code === 200) {
                    setData(res?.data);
                }
            })
            .finally(() => {
                setLoading(false);
                setIsRefresh(false);
            });
    }, [isRefresh]);

    return (
        <>
            <div style={{ border: '1px solid #f0f0f0', borderRadius: 8, padding: 24 }}>
                <div
                    style={{
                        display: 'flex',
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 10,
                    }}
                >
                    <div
                        style={{
                            fontWeight: 'bold',
                            fontSize: 16,
                        }}
                    >
                        查找:
                    </div>
                    <Search
                        placeholder="输入图片名称搜索"
                        onSearch={onSearch}
                        enterButton
                        allowClear
                        style={{
                            width: 300,
                        }}
                    />
                    <Button type="primary" onClick={() => setIsOpen(true)}>
                        新增图片
                    </Button>
                    {/* 右侧标题 */}
                    <div
                        style={{
                            marginLeft: 'auto',
                            fontWeight: 'bold',
                            fontSize: 16,
                            color: 'black',
                        }}
                    >
                        轮播图管理
                    </div>
                </div>
                <Table
                    columns={columns}
                    dataSource={data}
                    loading={loading}
                    rowKey="userId"
                    style={{
                        marginTop: 20,
                    }}
                />
            </div>
            <Dialog
                title="上传图片"
                dialogOpen={isOpen}
                onOk={() => form.submit()}
                onCancel={() => {
                    form.resetFields();
                    setIsOpen(false);
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={(values) => {
                        console.log('提交表单', values);
                        if (!values.image) {
                            return message.error('请选择要上传的图片');
                        }
                        const fileName = values.image?.file?.response?.data;
                        // 这里调用上传API，示例：
                        uploadCarouselForm(fileName, values?.title).then(() => {
                            message.success('上传成功');
                            setIsRefresh(!isRefresh);
                        });
                        setIsOpen(false);
                    }}
                >
                    <Form.Item label="图片标题" name="title" rules={[{ required: true, message: '请输入图片标题' }]}>
                        <Input placeholder="请输入图片名称（最多20字）" maxLength={20} />
                    </Form.Item>

                    <Form.Item
                        name="image"
                        label="上传图片"
                        rules={[{ required: true, message: '请选择要上传的图片' }]}
                    >
                        <Upload
                            listType="picture"
                            action={urlMap.defaultUrl + '/mana/carousel/upload'}
                            maxCount={1}
                            beforeUpload={(file) => {
                                const isImage = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type);
                                if (!isImage) {
                                    message.error('仅支持 PNG/JPG/JPEG 格式!');
                                }
                                return isImage;
                            }}
                            onRemove={() => {
                                // 新增删除回调
                                console.log('删除图片', form.getFieldValue('image'));
                                const fileName = form.getFieldValue('image')?.file?.response?.data;
                                return deleteCarousel(fileName).then(() => {
                                    message.success('删除成功');
                                    form.setFieldsValue({ image: null });
                                });
                            }}
                        >
                            <Button icon={<UploadOutlined />}>点击上传</Button>
                        </Upload>
                    </Form.Item>
                </Form>
            </Dialog>
        </>
    );
}

export default HomeMan;
